import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 晓星航
 * Date: 2023-12-05
 * Time: 8:50
 */
public class InsertPlus {
    public static int findMinValue(String numStr, int M) {
        int n = numStr.length();
        int[][] dp = new int[M + 1][n];

        // 初始化dp数组
        for (int i = 0; i <= M; i++) {
            Arrays.fill(dp[i], Integer.MAX_VALUE);
        }

        // 边界条件，不插入加号时的值即为原始数字串的值
        for (int j = 0; j < n; j++) {
            dp[0][j] = Integer.parseInt(numStr.substring(0, j + 1));
        }

        // 动态规划求解最小值
        for (int i = 1; i <= M; i++) {
            for (int j = i; j < n; j++) {
                for (int k = i - 1; k < j; k++) {
                    int val = Integer.parseInt(numStr.substring(k + 1, j + 1));
                    dp[i][j] = Math.min(dp[i][j], dp[i - 1][k] + val);
                }
            }
        }

        return dp[M][n - 1];
    }

    public static void main(String[] args) {
        String numStr = "123456789";
        int M = 3;
        int minValue = findMinValue(numStr, M);
        System.out.println("Minimum value: " + minValue);
    }
}
